<template>
  <!-- 查询条件卡片 -->
  <el-card style="margin-bottom: 10px;">
    <el-form :inline="true" class="demo-form-inline" style="margin-top: 10px;">
      <el-form-item label="货品">
        <el-input v-model="pageinfo.productName" placeholder="货品名称" clearable />
      </el-form-item>
      <el-form-item label="货品编号">
        <el-input v-model="pageinfo.productCode" placeholder="自动获取系统编号" class="readonly-input" readonly>
          <template #append>
            <el-button @click="generateInventoryCode" :loading="generatingInventoryCode">
              自动生成
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="货品类型">
        <el-cascader v-model="pageinfo.productTypeId" :options="productTypeOptions" :props="cascaderProps"
          placeholder="请选择货品类型" clearable filterable style="width: 220px;" />
      </el-form-item>
      <el-form-item label="单位">
        <el-select v-model="pageinfo.productUnit" placeholder="请选择单位" clearable filterable allow-create>
          <el-option v-for="unit in productUnits" :key="unit.unitId || unit.unitName" :label="unit.unitName"
            :value="unit.unitName" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库名称">
        <el-cascader v-model="pageinfo.warehouseId" :options="warehouseOptions" :props="warehouseCascaderProps"
          placeholder="请选择仓库" clearable filterable style="width: 220px;" />
      </el-form-item>
      <el-form-item label="货品条码">
        <el-input v-model="pageinfo.productBarcode" placeholder="货品条码" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="getInventoryList">搜索</el-button>
        <el-button type="info" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 筛选条件 -->
    <el-form :inline="true" style="margin-top: 10px;">
      <el-form-item label="停用商品">
        <el-switch v-model="pageinfo.showDisabled" @change="getInventoryList" />
      </el-form-item>
      <el-form-item label="零库存货品">
        <el-switch v-model="pageinfo.showZeroStock" @change="getInventoryList" />
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 统计信息卡片 -->
  <el-card style="margin-bottom: 10px;">
    <div style="display: flex; justify-content: space-around; text-align: center;">
      <div>
        <div style="font-size: 24px; font-weight: bold; color: #409EFF;">{{ statistics.totalProducts }}</div>
        <div style="color: #666;">当前库存货品</div>
      </div>
      <div>
        <div style="font-size: 24px; font-weight: bold; color: #67C23A;">{{ statistics.totalAmount.toFixed(2) }}</div>
        <div style="color: #666;">当前库存金额</div>
      </div>
      <div>
        <div style="font-size: 24px; font-weight: bold; color: #E6A23C;">{{ statistics.inStockCount }}</div>
        <div style="color: #666;">入库数量</div>
      </div>
      
      <div>
        <div style="font-size: 24px; font-weight: bold; color: #67C23A;">{{ statistics.waitInCount }}</div>
        <div style="color: #666;">待入库</div>
      </div>
      <div>
        <div style="font-size: 24px; font-weight: bold; color: #E6A23C;">{{ statistics.waitOutCount }}</div>
        <div style="color: #666;">待出库</div>
      </div>
    </div>
  </el-card>

  <!-- 库存列表数据 -->
  <el-card style="margin-bottom: 10px;">
    <el-button type="success" @click="exportData">
      <el-icon>
        <Download />
      </el-icon>导出
    </el-button>
    <el-button @click="getInventoryList">
      <el-icon>
        <Refresh />
      </el-icon>刷新
    </el-button>

    <el-table :data="tableData" style="width: 100%; margin-top: 10px;" height="440px" v-loading="loading">
      <el-table-column type="index" label="序号" width="55" fixed="left" />
      <el-table-column property="productCode" label="货品编号" width="120" fixed="left">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="goDetail(scope.row.productCode, scope.row.productId)">
            {{ scope.row.productCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column property="productName" label="货品名称" width="150" />
      <el-table-column property="productTypeName" label="货品类型" width="100" />
      <el-table-column property="productSpecification" label="规格" width="120" />
      <el-table-column property="productUnit" label="单位" width="80">
        <template #default="scope">
          {{ resolveUnitName(scope.row.productUnit, scope.row.unitName) }}
        </template>
      </el-table-column>
      <el-table-column property="productBarcode" label="货品条码" width="120" />
      <el-table-column property="warehouseName" label="仓库名称" width="100" />
      <el-table-column property="currentStock" label="当前库存" width="90" align="right">
        <template #default="scope">
          <span :class="{ 'zero-stock': scope.row.currentStock === 0 }">
            {{ scope.row.currentStock }}
          </span>
        </template>
      </el-table-column>
      <el-table-column property="inventoryMoney" label="库存金额" width="100" align="right">
        <template #default="scope">
          {{ scope.row.inventoryMoney?.toFixed?.(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column property="waitInStock" label="待入库" width="80" align="right" />
      <el-table-column property="waitOutStock" label="待出库" width="80" align="right" />
      <el-table-column property="lowerLimit" label="库存下限" width="90" align="right" />
      <el-table-column property="upperLimit" label="库存上限" width="90" align="right" />
      <el-table-column property="productInPrice" label="入库参考价" width="110" align="right">
        <template #default="scope">
          {{ scope.row.productInPrice?.toFixed?.(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column property="productOutPrice" label="出库参考价" width="110" align="right">
        <template #default="scope">
          {{ scope.row.productOutPrice?.toFixed?.(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column property="inventoryNote" label="备注" width="150" />
      <el-table-column label="操作人" width="180">
        <template #default="scope">
          {{ getOperator(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="操作时间" width="250">
        <template #default="scope">
          {{ getOperateTime(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column property="productStateName" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.productState === 1 ? 'success' : 'danger'" size="small">
            {{ scope.row.productState === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="scope">
          <el-button size="small" type="primary" @click="goDetail(scope.row.productCode, scope.row.productId)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 分页 -->
  <el-card>
    <el-pagination v-model:current-page="pageinfo.pageIndex" v-model:page-size="pageinfo.pageSize"
      :page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
      :total="pageinfo.total" @size-change="getInventoryList" @current-change="getInventoryList" />
  </el-card>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'
import { ElMessage } from 'element-plus'
import { Download, Refresh } from '@element-plus/icons-vue'

const router = useRouter()
const loading = ref(false)
const generatingInventoryCode = ref(false)

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const idxA = TIME_SEGMENT_ORDER.indexOf(a)
      const idxB = TIME_SEGMENT_ORDER.indexOf(b)
      if (idxA === -1 && idxB === -1) return 0
      if (idxA === -1) return 1
      if (idxB === -1) return -1
      return idxA - idxB
    })
  const timePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const serialLength = Number(rule?.serialLength ?? 3)
  const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
  return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode, targetName }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode, targetName }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateInventoryCode = async () => {
  if (generatingInventoryCode.value) return
  generatingInventoryCode.value = true
  try {
    pageinfo.productCode = await requestNumber('Inventory', '库存')
    ElMessage.success('编号生成成功')
  } catch (error: any) {
    ElMessage.error(error?.message || '生成编号失败')
  } finally {
    generatingInventoryCode.value = false
  }
}

// 分页查询条件
const pageinfo = reactive({
  pageIndex: 1,
  pageSize: 20,
  total: 0,
  productName: '',
  productCode: '',
  productBarcode: '',
  productTypeId: null as number | null,
  warehouseId: null as number | null,
  productUnit: '',
  showDisabled: true,
  showZeroStock: true
})

// 表格数据
const tableData = ref<any[]>([])

// 货品类型选项
const productTypeOptions = ref<any[]>([])
const cascaderProps = {
  value: 'producttypeId',
  label: 'producttypeName',
  children: 'children',
  checkStrictly: true,
  emitPath: false
}

// 仓库选项
const warehouseOptions = ref<any[]>([])
const warehouseCascaderProps = {
  value: 'warehouseId',
  label: 'warehouseName',
  children: 'children',
  checkStrictly: true,
  emitPath: false
}

// 货品单位选项
const productUnits = ref<any[]>([])
const unitNameMap = ref<Record<string, string>>({})

// 统计信息
const statistics = computed(() => {
  const stats = {
    totalProducts: tableData.value.length,
    totalAmount: 0,
    currentStockCount: 0,
    inStockCount: 0,
    outStockCount: 0,
    waitInCount: 0,
    waitOutCount: 0
  }

  tableData.value.forEach(item => {
    stats.totalAmount += item.inventoryMoney || 0
    stats.currentStockCount += item.currentStock || 0
    // 这里的入库数量和出库数量需要根据实际业务逻辑来计算
    // 暂时使用当前库存作为入库数量的基础
    stats.inStockCount += item.currentStock || 0
    stats.outStockCount += 0 // 出库数量需要从其他表获取
    stats.waitInCount += item.waitInStock || 0
    stats.waitOutCount += item.waitOutStock || 0
  })

  return stats
})

// 时间格式化
const formatTime = (time: string | null) => {
  if (!time) return ''
  const date = new Date(time)
  if (isNaN(date.getTime())) return time
  return date.toLocaleString('zh-CN')
}

const getOperator = (row: any) => {
  return row?.updater || row?.createor || ''
}

const getOperateTime = (row: any) => {
  const time = row?.updateTime || row?.createrTime || ''
  return formatTime(time)
}

// 跳转详情页
const goDetail = (code: string, productId?: number) => {
  if (!code) return
  const query: any = { productCode: code }
  if (productId) {
    query.productId = productId
  }
  router.push({ path: '/ProductDetail', query })
}

// 获取库存列表
const getInventoryList = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: pageinfo.pageIndex,
      pageSize: pageinfo.pageSize,
      productName: pageinfo.productName || undefined,
      productCode: pageinfo.productCode || undefined,
      productBarcode: pageinfo.productBarcode || undefined,
      productTypeId: pageinfo.productTypeId || undefined,
      warehouseId: pageinfo.warehouseId || undefined,
      productUnit: pageinfo.productUnit || undefined,
      showDisabled: pageinfo.showDisabled,
      showZeroStock: pageinfo.showZeroStock
    }

    const res = await myaxios({
      url: '/api/Inventory/GetInventoryPage',
      method: 'get',
      params
    })

    if (res.data.code === 200) {
      tableData.value = res.data.data.data || []
      pageinfo.total = res.data.data.listCount || 0
    } else {
      ElMessage.error(res.data.message || '获取库存数据失败')
    }
  } catch (error) {
    console.error('获取库存数据失败:', error)
    ElMessage.error('获取库存数据失败')
  } finally {
    loading.value = false
  }
}

// 获取货品类型（树形结构）
const getProductTypes = async () => {
  try {
    const res = await myaxios({
      url: '/api/Product/GetProductType',
      method: 'get'
    })

    if (res.data.code === 200) {
      const types = res.data.data || []
      productTypeOptions.value = buildTree(types, 'producttypeId', 'producttypeParentid')
    }
  } catch (error) {
    console.error('获取货品类型失败:', error)
  }
}

// 获取仓库列表
const getWarehouses = async () => {
  try {
    const res = await myaxios({
      url: '/api/Product/GetWarehouse',
      method: 'get'
    })

    if (res.data.code === 200) {
      const warehouses = res.data.data || []
      warehouseOptions.value = warehouses.map((w: any) => ({
        warehouseId: w.warehouseId,
        warehouseName: w.warehouseName
      }))
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

// 获取货品单位
const normalizeUnitKey = (value: unknown) => {
  if (value === null || value === undefined) return ''
  return String(value).trim()
}

const resolveUnitName = (value: unknown, fallback?: unknown) => {
  const potentialKeys = [
    normalizeUnitKey(value),
    normalizeUnitKey(fallback)
  ].filter(Boolean)
  for (const key of potentialKeys) {
    if (key && unitNameMap.value[key]) {
      return unitNameMap.value[key]
    }
  }
  return potentialKeys[0] || ''
}

const getProductUnits = async () => {
  try {
    const res = await myaxios({
      url: '/api/Inventory/GetProductUnits',
      method: 'get'
    })

    if (res.data.code === 200) {
      const units = Array.isArray(res.data.data) ? res.data.data : []
      productUnits.value = units
      const lookup: Record<string, string> = {}
      units.forEach((unit: any) => {
        const idKey = normalizeUnitKey(unit?.unitId)
        const nameKey = normalizeUnitKey(unit?.unitName)
        const codeKey = normalizeUnitKey(unit?.unitCode)
        if (idKey) lookup[idKey] = unit.unitName
        if (nameKey) lookup[nameKey] = unit.unitName
        if (codeKey) lookup[codeKey] = unit.unitName
      })
      unitNameMap.value = lookup
    }
  } catch (error) {
    console.error('获取货品单位失败:', error)
  }
}

// 构建树形结构
const buildTree = (items: any[], idKey: string, parentIdKey: string) => {
  const tree: any[] = []
  const map: { [key: string]: any } = {}

  // 创建映射
  items.forEach(item => {
    map[item[idKey]] = { ...item, children: [] }
  })

  // 构建树
  items.forEach(item => {
    const parentId = item[parentIdKey]
    if (parentId && map[parentId]) {
      map[parentId].children.push(map[item[idKey]])
    } else {
      tree.push(map[item[idKey]])
    }
  })

  return tree
}

// 重置搜索条件
const resetSearch = () => {
  pageinfo.productName = ''
  pageinfo.productCode = ''
  pageinfo.productBarcode = ''
  pageinfo.productTypeId = null
  pageinfo.warehouseId = null
  pageinfo.productUnit = ''
  pageinfo.showDisabled = true
  pageinfo.showZeroStock = true
  pageinfo.pageIndex = 1
  getInventoryList()
}

// 导出数据
const exportData = () => {
  const params = new URLSearchParams({
    pageIndex: '1',
    pageSize: '10000',
    productName: pageinfo.productName || '',
    productCode: pageinfo.productCode || '',
    productBarcode: pageinfo.productBarcode || '',
    productTypeId: pageinfo.productTypeId?.toString() || '',
    warehouseId: pageinfo.warehouseId?.toString() || '',
    productUnit: pageinfo.productUnit || '',
    showDisabled: pageinfo.showDisabled.toString(),
    showZeroStock: pageinfo.showZeroStock.toString()
  })

  window.open(`http://localhost:8080/api/Inventory/ExportInventory?${params.toString()}`)
}

// 页面加载时初始化数据
onMounted(() => {
  getInventoryList()
  getProductTypes()
  getWarehouses()
  getProductUnits()
})
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.zero-stock {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-table .el-table__header-wrapper th) {
  background-color: #f5f7fa;
}

:deep(.readonly-input .el-input__wrapper) {
  background-color: #f5f7fa;
}
</style>
